package com.gl.basis.zuul.util;

import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.gl.basis.auth.constants.AuthorityConstants;

import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;
@Slf4j
public class CommonUtil {

	public static String getUserInput() {
		String input = "";
		Scanner scanner = new Scanner(System.in, "utf8");
		input = scanner.next();
		return input;
	}

	/**
	 * 按key进行正序排列，之间以&相连 <功能描述>
	 * 
	 * @param params
	 * @return
	 */
	public static String getSortParams(Map<String, String> params) {
		Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
			public int compare(String obj1, String obj2) {
				// 升序排序
				return obj1.compareTo(obj2);
			}
		});
		for (String key : params.keySet()) {
			map.put(key, params.get(key));
		}

		Set<String> keySet = map.keySet();
		Iterator<String> iter = keySet.iterator();
		String str = "";
		while (iter.hasNext()) {
			String key = iter.next();
			String value = map.get(key);
			str += key + "=" + value + "&";
		}
		if (str.length() > 0) {
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}
	
	/**
	 * 生成待签字符串
	 *
	 * @param data 原始map数据
	 * @return 待签字符串
	 */
	public static String buildWaitingForSign(Map<String, String> data) {
		if (data == null || data.size() == 0) {
			throw new IllegalArgumentException("请求数据不能为空");
		}
		String waitingForSign = null;
		Map<String, String> sortedMap = new TreeMap<>(data);
		// 如果sign参数存在,去除sign参数,不参与签名
		if (sortedMap.containsKey(AuthorityConstants.SIGN)) {
			sortedMap.remove(AuthorityConstants.SIGN);
		}
		StringBuilder stringToSign = new StringBuilder();
		for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
			if (entry.getValue() != null) {
				stringToSign.append(entry.getKey()).append("=").append(JSON.toJSONString(entry.getValue())).append("&");
			}
		}
		stringToSign.deleteCharAt(stringToSign.length() - 1);
		waitingForSign = stringToSign.toString();
		log.debug("代签名字符串:{}", waitingForSign);
		return waitingForSign;
	}
	
}
